/**
 * 统一脚本文件
 * 为所有页面提供通用功能
 */

document.addEventListener('DOMContentLoaded', function() {
    // 侧边栏切换
    const menuToggle = document.querySelector('.menu-toggle');
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (menuToggle && sidebar && mainContent) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        });
    }
    
    // 侧边栏菜单项高亮
    const currentPath = window.location.pathname;
    const menuItems = document.querySelectorAll('.sidebar-menu a');
    
    menuItems.forEach(item => {
        const href = item.getAttribute('href');
        if (href && currentPath.includes(href)) {
            item.classList.add('active');
            
            // 如果是子菜单，展开父菜单
            const parentMenuItem = item.closest('.submenu-container');
            if (parentMenuItem) {
                parentMenuItem.classList.add('expanded');
            }
        }
    });
    
    // 子菜单展开/折叠
    const submenuToggles = document.querySelectorAll('.submenu-toggle');
    
    submenuToggles.forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            const container = this.closest('.submenu-container');
            container.classList.toggle('expanded');
        });
    });
    
    // 用户菜单展开/折叠
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    const userMenu = document.querySelector('.user-dropdown');
    
    if (userMenuToggle && userMenu) {
        userMenuToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            userMenu.classList.toggle('visible');
            
            // 点击其他区域关闭菜单
            const clickOutside = function(event) {
                if (!userMenu.contains(event.target) && !userMenuToggle.contains(event.target)) {
                    userMenu.classList.remove('visible');
                    document.removeEventListener('click', clickOutside);
                }
            };
            
            document.addEventListener('click', clickOutside);
        });
    }
    
    // 暗黑模式切换
    const darkModeToggle = document.querySelector('.dark-mode-toggle');
    
    if (darkModeToggle) {
        // 检查本地存储中的暗黑模式设置
        const isDarkMode = localStorage.getItem('darkMode') === 'true';
        
        // 应用初始模式
        if (isDarkMode) {
            document.body.classList.add('dark-mode');
            darkModeToggle.textContent = '🌙';
        } else {
            darkModeToggle.textContent = '☀️';
        }
        
        // 切换模式
        darkModeToggle.addEventListener('click', function() {
            document.body.classList.toggle('dark-mode');
            
            const isNowDark = document.body.classList.contains('dark-mode');
            localStorage.setItem('darkMode', isNowDark);
            
            if (isNowDark) {
                darkModeToggle.textContent = '🌙';
            } else {
                darkModeToggle.textContent = '☀️';
            }
        });
    }
    
    // 表格排序功能
    const sortableTables = document.querySelectorAll('.table-sortable');
    
    sortableTables.forEach(table => {
        const headers = table.querySelectorAll('th.sortable');
        
        headers.forEach(header => {
            header.addEventListener('click', function() {
                const isAscending = !this.classList.contains('sort-asc');
                
                // 移除所有排序标记
                headers.forEach(h => {
                    h.classList.remove('sort-asc', 'sort-desc');
                });
                
                // 添加当前排序标记
                this.classList.add(isAscending ? 'sort-asc' : 'sort-desc');
                
                // 获取要排序的列索引
                const columnIndex = Array.from(this.parentNode.children).indexOf(this);
                
                // 获取表格内容
                const tbody = table.querySelector('tbody');
                const rows = Array.from(tbody.querySelectorAll('tr'));
                
                // 排序行
                rows.sort((a, b) => {
                    const aValue = a.children[columnIndex].textContent.trim();
                    const bValue = b.children[columnIndex].textContent.trim();
                    
                    // 尝试数字排序
                    const aNum = parseFloat(aValue);
                    const bNum = parseFloat(bValue);
                    
                    if (!isNaN(aNum) && !isNaN(bNum)) {
                        return isAscending ? aNum - bNum : bNum - aNum;
                    }
                    
                    // 字符串排序
                    return isAscending ? 
                        aValue.localeCompare(bValue, 'zh-CN') : 
                        bValue.localeCompare(aValue, 'zh-CN');
                });
                
                // 重新添加排序后的行
                rows.forEach(row => {
                    tbody.appendChild(row);
                });
            });
        });
    });
    
    // 过滤表格功能
    const tableFilters = document.querySelectorAll('.table-filter input');
    
    tableFilters.forEach(filter => {
        filter.addEventListener('input', function() {
            const table = document.querySelector(this.getAttribute('data-target'));
            if (!table) return;
            
            const rows = table.querySelectorAll('tbody tr');
            const query = this.value.toLowerCase();
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(query) ? '' : 'none';
            });
        });
    });
    
    // 添加波纹效果到所有按钮
    const buttons = document.querySelectorAll('.btn');
    
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            const rect = button.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const ripple = document.createElement('span');
            ripple.className = 'ripple';
            ripple.style.left = x + 'px';
            ripple.style.top = y + 'px';
            
            button.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
    
    // 折叠面板功能
    const collapsibleHeaders = document.querySelectorAll('.collapsible-header');
    
    collapsibleHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const content = this.nextElementSibling;
            this.classList.toggle('expanded');
            
            if (content.style.maxHeight) {
                content.style.maxHeight = null;
            } else {
                content.style.maxHeight = content.scrollHeight + 'px';
            }
        });
        
        // 默认展开有active类的折叠面板
        if (header.classList.contains('active')) {
            const content = header.nextElementSibling;
            header.classList.add('expanded');
            content.style.maxHeight = content.scrollHeight + 'px';
        }
    });
    
    // 自定义下拉框功能
    const customSelects = document.querySelectorAll('.custom-select');
    
    customSelects.forEach(select => {
        const selectWrapper = document.createElement('div');
        selectWrapper.className = 'select-wrapper';
        
        const selectedOption = document.createElement('div');
        selectedOption.className = 'selected-option';
        selectedOption.textContent = select.options[select.selectedIndex].textContent;
        
        const optionsList = document.createElement('div');
        optionsList.className = 'options-list';
        
        Array.from(select.options).forEach(option => {
            const optionItem = document.createElement('div');
            optionItem.className = 'option-item';
            optionItem.textContent = option.textContent;
            optionItem.dataset.value = option.value;
            
            if (option.selected) {
                optionItem.classList.add('selected');
            }
            
            optionItem.addEventListener('click', function() {
                select.value = this.dataset.value;
                selectedOption.textContent = this.textContent;
                
                // 触发change事件
                const event = new Event('change');
                select.dispatchEvent(event);
                
                // 更新选中状态
                optionsList.querySelectorAll('.option-item').forEach(item => {
                    item.classList.remove('selected');
                });
                this.classList.add('selected');
                
                // 关闭下拉列表
                optionsList.classList.remove('visible');
            });
            
            optionsList.appendChild(optionItem);
        });
        
        selectedOption.addEventListener('click', function(e) {
            e.stopPropagation();
            optionsList.classList.toggle('visible');
            
            // 点击其他区域关闭下拉列表
            const clickOutside = function(event) {
                if (!selectWrapper.contains(event.target)) {
                    optionsList.classList.remove('visible');
                    document.removeEventListener('click', clickOutside);
                }
            };
            
            document.addEventListener('click', clickOutside);
        });
        
        selectWrapper.appendChild(selectedOption);
        selectWrapper.appendChild(optionsList);
        
        // 隐藏原始下拉框，插入自定义下拉框
        select.style.display = 'none';
        select.parentNode.insertBefore(selectWrapper, select.nextSibling);
        
        // 监听原始下拉框变化
        select.addEventListener('change', function() {
            selectedOption.textContent = this.options[this.selectedIndex].textContent;
            
            optionsList.querySelectorAll('.option-item').forEach(item => {
                item.classList.remove('selected');
                if (item.dataset.value === this.value) {
                    item.classList.add('selected');
                }
            });
        });
    });
    
    // 标签页切换功能
    const tabButtons = document.querySelectorAll('.tab-btn');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tabGroup = this.closest('.tab-group');
            const tabId = this.getAttribute('data-tab');
            
            // 更新标签按钮状态
            tabGroup.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            this.classList.add('active');
            
            // 更新标签内容显示
            tabGroup.querySelectorAll('.tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            const targetTab = document.getElementById(tabId);
            if (targetTab) {
                targetTab.style.display = 'block';
            }
        });
    });
    
    // 页面加载时自动点击第一个标签
    const tabGroups = document.querySelectorAll('.tab-group');
    tabGroups.forEach(group => {
        const firstTab = group.querySelector('.tab-btn');
        if (firstTab) {
            firstTab.click();
        }
    });
    
    // 工具提示功能
    const tooltips = document.querySelectorAll('[data-tooltip]');
    
    tooltips.forEach(element => {
        element.addEventListener('mouseenter', function() {
            const tooltipText = this.getAttribute('data-tooltip');
            
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = tooltipText;
            
            document.body.appendChild(tooltip);
            
            const rect = this.getBoundingClientRect();
            const tooltipRect = tooltip.getBoundingClientRect();
            
            tooltip.style.top = rect.top - tooltipRect.height - 10 + 'px';
            tooltip.style.left = rect.left + (rect.width - tooltipRect.width) / 2 + 'px';
            
            tooltip.classList.add('visible');
            
            this.addEventListener('mouseleave', function onMouseLeave() {
                tooltip.classList.remove('visible');
                
                setTimeout(() => {
                    if (tooltip.parentNode) {
                        document.body.removeChild(tooltip);
                    }
                }, 200);
                
                this.removeEventListener('mouseleave', onMouseLeave);
            });
        });
    });
}); 